import {
  ContentBlockDeltaEvent,
  MessageStreamEvent,
} from "@anthropic-ai/sdk/resources/index.mjs";
export const ClaudeApi = () => {
  const { getSetValue } = chatSettingStore();
  const apiConfig = getSetValue("api");
  const sendMessage = async (
    messages: Message[],
    handler: (content: ExtendedChatCompletionChunk) => void
  ) => {
    const { unListen, response } = await useTauriRequest(
      apiConfig("apiUrl"),
      {
        messages: messages.map((e) => ({
          role: e.role,
          content: e.content,
        })),
        model: apiConfig("modelName") ?? "claude-3-haiku-20240307",
        stream: apiConfig("stream"),
        max_tokens: apiConfig("max_tokens"),
      },
      {
        responseType: "STREAM",
        method: "POST",
        headers: {
          accept: "application/json",
          "anthropic-version": "2023-06-01",
          "x-api-key": apiConfig("Authorization"),
        },
      },
      (data) => {
        data.split("event:").map((e) => {
          const data = e.split("data:")[1];
          if (data) {
            const jsonData: MessageStreamEvent = JSON.parse(data);
            console.log(jsonData.type);
            if (jsonData.type === "content_block_delta") {
              const data = jsonData as ContentBlockDeltaEvent;
              handler(createMessage(data.delta.text));
            }
            if (jsonData.type === "content_block_stop") {
              handler(createStopMessage());
            }
            if (jsonData.type === "message_stop") {
              unListen!();
            }
          }
        });
      }
    );
    if ((response as any).error) {
      handler(createErrorMessage((response as any).error.message));
      unListen!();
    }
  };
  return {
    sendMessage,
  };
};
